import assetsStore from '../store/assets';
import { toRaw } from 'vue';
import { StoreDefinition } from 'pinia';
import eventsStore from '../store/events';
import { scenesStore } from '../store/scenes';
import axios from 'axios';

const KEY = 'sail';


export class DataBase {
    private getStores(): Array<StoreDefinition> {
        return [assetsStore, eventsStore, scenesStore];
    }
    
    init(): any {
        const str = localStorage.getItem(KEY);
        if (str) {
            const data: any = JSON.parse(str);
            const stores = this.getStores();
            for (let i = 0; i < stores.length; i++) {
                const storeDef: StoreDefinition = stores[i];
                const store = storeDef();
                
                if (!store.toConfig) {
                    console.error(`store no toConfig function: ${store.$id}`);
                    continue;
                }
                const { key } = store.toConfig();
                if (key && data[key]) {
                    
                    if (!store.init) {
                        console.error(`store no init function: ${store.$id}`);
                    }
                    store.init(data[key]);
                }
            }
        }
    }
    
    
    save(): void {
        const data: any = {};
        const stores = this.getStores();
        for (let i = 0; i < stores.length; i++) {
            const storeDef: StoreDefinition = stores[i];
            const store = storeDef();
            if (!store.toConfig) {
                continue;
            }
            const { key } = store.toConfig();
            data[key] = toRaw(store.$state);
        }
        const str = JSON.stringify(data);
        localStorage.setItem(KEY, str);
    }
    
    sync2local() {
        const data = localStorage.getItem(KEY);
        axios.post('http://localhost:2022/save', data).then(() => {
        
        });
    }
}

const db = new DataBase();
export default db;